package com.liser.print.bluetooth;

import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import com.liser.print.bluetooth.callback.BaseCallback;
import com.liser.print.bluetooth.callback.ConnectCallback;
import com.liser.print.bluetooth.callback.ScanCallback;
import com.liser.print.bluetooth.callback.SendCallback;
import com.liser.print.bluetooth.callback.SwitchCallback;
import com.liser.print.bluetooth.receiver.BtConnectReceiver;
import com.liser.print.bluetooth.receiver.BtScanReceiver;
import com.liser.print.bluetooth.receiver.BtSwitchReceiver;
import com.liser.print.bluetooth.service.BtClientService;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import io.reactivex.Observable;


/**
 * @author Administrator
 * @date 2020/1/14 13:54
 */
public class BtManager implements BaseCallback {

    private Application mContext;

    /**
     * 蓝牙适配器
     */
    private BluetoothAdapter mBluetoothAdapter;

    private BtSwitchReceiver btSwitchReceiver;

    private BtScanReceiver btScanReceiver;

    private BtConnectReceiver btConnectReceiver;

    /**
     * 蓝牙开关回调
     */
    private SwitchCallback mSwitchCallback;

    /**
     * 扫描设备回调
     */
    private ScanCallback mScanCallback;

    /**
     * 连接设备回调
     */
    private ConnectCallback mConnectCallback;

    public static BtManager getInstance() {
        return BtManagerHolder.BT_MANAGER;
    }

    private static class BtManagerHolder {
        private static final BtManager BT_MANAGER = new BtManager();
    }

    /**
     * 初始化
     *
     * @param app 应用
     * @return 对象
     */
    public BtManager init(Application app) {
        if (mContext == null && app != null) {
            mContext = app;
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            btSwitchReceiver = new BtSwitchReceiver(mContext, this);
            btScanReceiver = new BtScanReceiver(mContext, this);
            btConnectReceiver = new BtConnectReceiver(mContext, this);
        }
        return this;
    }

    @Override
    public void onStateSwitch(int state) {
        if (mSwitchCallback == null) {
            return;
        }
        if (state == BluetoothAdapter.STATE_ON) {
            mSwitchCallback.onStateChange(true);
        } else if (state == BluetoothAdapter.STATE_OFF) {
            mSwitchCallback.onStateChange(false);
        }
    }

    @Override
    public void onScanStart() {
        if (mScanCallback == null) {
            return;
        }
        mScanCallback.onScanStart();
    }

    @Override
    public void onScanStop() {
        if (mScanCallback == null) {
            return;
        }
        mScanCallback.onScanStop();
    }

    @Override
    public void onFindDevice(BluetoothDevice device) {
        if (mScanCallback == null) {
            return;
        }
        mScanCallback.onFindDevice(device);
    }

    @Override
    public void onConnect(BluetoothDevice device) {
        if (mConnectCallback == null) {
            return;
        }
        BtClientService.getInstance().isConnection = true;
        mConnectCallback.connectSuccess(BtClientService.getInstance().getBluetoothSocket(), device);
    }

    @Override
    public void onDisconnect(BluetoothDevice device) {
        if (mConnectCallback == null) {
            return;
        }
        BtClientService.getInstance().cancel();
        mConnectCallback.connectClose(device);
    }

    /**
     * 判断是否支持蓝牙
     */
    public boolean isSupportedBluetooth() {
        return mBluetoothAdapter != null;
    }

    /**
     * 判断是否开启蓝牙
     */
    public boolean isEnableBluetooth() {
        return mBluetoothAdapter.isEnabled();
    }

    /**
     * 开启蓝牙
     */
    public void enableBluetooth(SwitchCallback switchCallback) {
        mSwitchCallback = switchCallback;
        if (mBluetoothAdapter != null) {
            if (!mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.enable();
            } else {
                mSwitchCallback.onStateChange(true);
            }
        }
    }

    /**
     * 关闭蓝牙
     */
    public void disableBluetooth(SwitchCallback switchCallback) {
        mSwitchCallback = switchCallback;
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isEnabled()) {
                mBluetoothAdapter.disable();
            }
        }
    }

    /**
     * 开始搜索
     */
    public void startScan(ScanCallback scanCallback) {
        mScanCallback = scanCallback;
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isDiscovering()) {
                return;
            }
            mBluetoothAdapter.startDiscovery();
        }
    }

    /**
     * 取消搜索
     */
    public void stopScan() {
        if (mBluetoothAdapter != null) {
            if (mBluetoothAdapter.isDiscovering()) {
                mBluetoothAdapter.cancelDiscovery();
            }
        }
    }

    /**
     * 已配对设备列表
     */
    public Set<BluetoothDevice> getBondedDevices() {
        return mBluetoothAdapter.getBondedDevices();
    }

    /**
     * 设备连接
     */
    public void connectDevice(BluetoothDevice device, ConnectCallback connectCallback) {
        mConnectCallback = connectCallback;
        if (mBluetoothAdapter != null) {
            //配对蓝牙
            BtClientService.getInstance().init(mBluetoothAdapter, device, mConnectCallback);
        }
    }

    public BluetoothDevice connectedDevice() {
        return BtClientService.getInstance().connectedBluetooth();
    }

    /**
     * 发送数据
     */
    public void sendData(byte[] data, SendCallback callback) {
        if (BtClientService.getInstance().isConnection) {
            List<byte[]> bytes = new ArrayList<>();
            bytes.add(data);
            BtClientService.getInstance().sendData(bytes, callback);
        } else {
            callback.sendError(new Exception("设备未连接"));
        }
    }

    public Observable<String> sendData(byte[] data) {
        return BtClientService.getInstance().sendData(data);
    }

    /**
     * 关闭蓝牙客户端
     */
    public void closeClientSide() {
        try {
            BtClientService.getInstance().cancel();
        } catch (Exception e) {
        }
    }

    /**
     * 关闭服务
     */
    public void onDestroy() {
        try {
            BtClientService.getInstance().cancel();
        } catch (Exception e) {
        }
        mContext.unregisterReceiver(btSwitchReceiver);
        mContext.unregisterReceiver(btScanReceiver);
        mContext.unregisterReceiver(btConnectReceiver);
    }
}
